package com.imooc.spark

import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
  * Created by zghgchao 2017/11/15 9:36
  * Spark Streaming处理Socket数据
  *  172.17.66.107：
  * nc -lk 9999
  */
object NetworkCount {

  def main(args: Array[String]): Unit = {
    val sparkConf = new SparkConf().setMaster("local[2]").setAppName("NetworkCount")

    /**
      * 创建StreamingContext需要两个参数：SparkConf和batch interval
      */
    val ssc = new StreamingContext(sparkConf, Seconds(5))

    //如果使用了stateful的算子，必须设置checkpoint
    //在生产环境中，建议把checkpoint设置到HDFS的某个文件夹中
//    ssc.checkpoint(".")

    val lines = ssc.socketTextStream("172.17.66.107", 9999)

    val result = lines.flatMap(_.split(" ")).map((_, 1)).reduceByKey(_ + _)

    result.print()

    ssc.start()

    ssc.awaitTermination()

  }
}
